import { Component,SimpleChange, OnInit, AfterViewInit,AfterViewChecked,OnChanges, ElementRef  } from '@angular/core';
import { Router,ActivatedRoute }   from '@angular/router';
import { MdDialog } from '@angular/material';

import { User }             from '../../domain/user.mdl';
import { UserService }      from '../../services/user.service';
import { UserDialogForm }   from './components/user.dialog.form';

function initBSSWitch(){
  $.fn.bootstrapSwitch.defaults.size = 'mini';
  $.fn.bootstrapSwitch.defaults.onColor = 'success';
  $.fn.bootstrapSwitch.defaults.onText = '正常';
  $.fn.bootstrapSwitch.defaults.offText = '禁用';
}

//*

function configBSSWitch(cb){
  var bssCtrls = $("input:checkbox[class='bsscb']");
  //console.log(bssCtrls.length);
  for(var i=0;i<bssCtrls.length;i++) {
    var cbObj = bssCtrls[i];
    //cbObj.bootstrapSwitch();
    console.log(cbObj);
  }

  //for(let cbObj of bssCtrls){
    //var cbObj = bssCtrls[i];
    //console.log(cbObj.name);
    //cbObj.bootstrapSwitch();
    //cbObj.on('switchChange.bootstrapSwitch', function(event, state) {
    //  console.log(this.name,state);
    //});
  //}
  //console.log('configBSSWitch over.');
}

//*/
function configSwitch(sname,cb){
  //console.log('sname=',sname);
  var bssBt = $("input:checkbox[name='"+sname+"']");
  var value = bssBt.val();
  //console.log('val():',value);
  if(value=='1') bssBt.attr('checked','true');

  bssBt.bootstrapSwitch();
  //bssBt.bootstrapSwitch('setState',value);
  //bssBt.bootstrapSwitch();
  //console.log('cool');
  bssBt.on('switchChange.bootstrapSwitch', function(event, state) {
    //console.log(typeof event.currentTarget,this.name); // DOM element
    //console.log(event.target); // jQuery event
    //console.log(event.data.value,state);
    //console.log(event.target.nodeName,state);
    console.log('value:',this.value); // true | false
    if(cb) {
      cb(this.name,state);
    }
  });
  //console.log('configSwitch call over.');
}

var DlgConfig = {
  disableClose:true,
  hasBackdrop:true,
  width:'680px',
  height:'520px'
};

@Component({
  selector: 'user',
  templateUrl: 'user.component.html',
  styles: [
    `.clkt {
      cursor: pointer;
    }`
  ]
})

export class UserComponent  implements OnInit {
  users:User[] = [];
  private errMsg: string;
  //private bssInited:boolean = false;

  constructor(private _elementRef: ElementRef,private router: Router,
    private userService:UserService,
    public dialog: MdDialog) {
      //
  }
  //,AfterViewInit,AfterViewChecked, OnChanges

  ngOnInit(): void {
    initBSSWitch();
    this.getUsers();    
    console.log('ngOnInit call over.');
  }
  
  updateUserStatus(uid:string,state:boolean):void{
    console.log(uid,state);
    //layer.msg(`${uid}:${state}`);
    var reqData = {uid:uid,status:state?'1':'0'};
    console.log(reqData);
    this.userService.updateUserStatus(reqData).subscribe(
      res => {
        console.log('res:',res);
      },
      errMsg => {
        this.errMsg = errMsg;
        console.log('errMsg:',this.errMsg);
      }
    );
  }

  setCheckBox():boolean {
    if(this.users && this.users.length > 0){
      for(let user of this.users){
        configSwitch(user._id,(name,state)=>{
          this.updateUserStatus(name,state);          
        });
      }
      return true;
    }else{
      console.log('this.users is null');
      return false;
    }
  }

  getUsers(): void {
    this.userService.getUsers().subscribe(
      users => {
        this.users = users;
        setTimeout(()=>{this.setCheckBox()},100);
        //setTimeout(()=>{configBSSWitch(null)},100);
      },
      errMsg => this.errMsg = errMsg
    );
  }
  
  ngOnChanges(changes: {[propName: string]: SimpleChange}): void {
    console.log('Changes', changes);
  }

  onUserAdded(user: User):void {
    this.users.unshift(user);
  }

  onUserDeleted(uid: string):void {
    this.users = this.users.filter(function(user){
      return user._id != uid;
    });
  }

  deleteUser(uid:string):void {
    layerHelper.confirm('确信要删除这个管理员吗?', 
      '删除确认',
      (index) => {
      this.userService.deleteUser(uid).subscribe(res=>{
        if(res == 'success'){
          layer.msg('删除成功.');
          this.onUserDeleted(uid);
        }else{
          layer.msg('删除失败:'+res);
        }
      },
      errMsg => {
        console.error(errMsg);
      });
    });
  }

  openAddDlg():void {
    let dialogRef = this.dialog.open(UserDialogForm,DlgConfig);
    dialogRef.afterClosed().subscribe(user => {
      //console.log('user=',JSON.stringify(user,null,2));
      if(user!=''){
        this.users.unshift(user);
      }
    });
  }

  openEditDlg(formData:any):void {
    let dialogRef = this.dialog.open(UserDialogForm,
      $.extend({}, DlgConfig,{data:formData}));
    /*
    dialogRef.afterClosed().subscribe(result => {
      console.log(`Dialog result: ${result}`);
    });//*/
  }
}

